package edu.qichen.onlineBlog.framework.validata;

import edu.qichen.onlineBlog.framework.validata.annptation.AtLeastOneNotNull;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class AtLeastOneNotNullValidator implements ConstraintValidator<AtLeastOneNotNull, Object> {
    private List<String> fieldNames;


    @Override
    public void initialize(AtLeastOneNotNull constraintAnnotation) {
        this.fieldNames = Arrays.asList(constraintAnnotation.value());
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }

        Class<?> clazz = value.getClass();
        boolean atLeastOneNotNull = false;

        for (String fieldName : fieldNames) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                if (field.get(value) != null) {
                    atLeastOneNotNull = true;
                    break;
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                // 如果字段不存在或无法访问，抛出异常或记录错误
                throw new IllegalStateException("Field " + fieldName + " does not exist or is not accessible", e);
            }
        }

        return atLeastOneNotNull;
    }
}